<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>

<form class="layui-form" lay-filter="search" id="search" style="padding-top: 10px">
    <div class="layui-form-item">
        <!--        layui-inline,外层行内-->
        <div class="layui-inline">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-inline">
                <input type="text" name="username" placeholder="请输入用户名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <button class="layui-btn" lay-submit lay-filter="formDemo">查询</button>
            <button type="reset" id="searchReset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<!--添加表单-->
<form class="layui-form" action="" style="display: none" id="addUser" lay-filter="editBusinessFormFilter">
    <!-- 这里设置一个隐藏域，用来存放我们的图片的地址 -->
    <div class="layui-form-item">
        <label class="layui-form-label" username style="width: 100px">用户名</label>
        <div class="layui-input-inline">
            <input type="text" id="addUsername" name="addUsername" required lay-verify="required" placeholder="请输入用户名"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" password style="width: 100px">密码</label>
        <div class="layui-input-inline">
            <input type="text" id="addPassword" name="addPassword" required lay-verify="required" placeholder="请输入密码"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item  layui-form" lay-filter="selFilter">
        <label class="layui-form-label" gender style="width: 100px">性别</label>
        <div class="layui-input-inline">
            <select id="addGender" lay-verify="required" name="addGender">
                <option value="">请选择</option>
                <option value="0">女</option>
                <option value="1">男</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" age style="width: 100px">出生日期</label>
        <div class="layui-input-inline">
            <input id="addBirthday" class="layui-input" name="addBirthday" lay-verify="required" placeholder="出生日期"/>
        </div>
    </div>


    <div class="layui-form-item">
        <label class="layui-form-label" phone style="width: 100px">电话号码</label>
        <div class="layui-input-inline">
            <input type="text" id="addPhone" name="addPhone" required lay-verify="required|newmobile"
                   placeholder="请输入电话号码"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="addSubmit">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<!--编辑表单-->
<form class="layui-form" action="" style="display: none" id="editUser" lay-filter="editBusinessFormFilter">
    <!-- 这里设置一个隐藏域，用来存放我们的图片的地址 -->
    <input type="hidden" id="id" name="id" value="">
    <div class="layui-form-item">
        <label class="layui-form-label" username style="width: 100px">用户名</label>
        <div class="layui-input-inline">
            <input type="text" id="username" name="username" required lay-verify="required" placeholder="请输入用户名"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label" password style="width: 100px">用户名</label>
        <div class="layui-input-inline">
            <input type="text" id="password" name="password" required lay-verify="required" placeholder="请输入密码"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item  layui-form" lay-filter="selFilter">
        <label class="layui-form-label" gender style="width: 100px">性别</label>
        <div class="layui-input-inline">
            <select id="gender" lay-verify="required" name="gender">
                <option value="">请选择</option>
                <option value="0">女</option>
                <option value="1">男</option>

            </select>
        </div>
    </div>


    <div class="layui-form-item">
        <label class="layui-form-label" age style="width: 100px">出生日期</label>
        <div class="layui-input-inline">
            <input id="birthday" class="layui-input" name="birthday" lay-verify="required" placeholder="出生日期"/>
        </div>
    </div>


    <div class="layui-form-item">
        <label class="layui-form-label" phone style="width: 100px">电话号码</label>
        <div class="layui-input-inline">
            <input type="text" id="phone" name="phone" required lay-verify="required|newmobile" placeholder="请输入电话号码"
                   autocomplete="off"
                   class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="editSubmit">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<!--user数据表格-->
<table class="layui-hide" id="test" lay-filter="demo"></table>


<script src="/layui/layui.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->
<script>
    layui.use(['table', 'jquery', 'form', 'upload', 'laydate'], function () {
        var table = layui.table;
        var $ = layui.$,
            form = layui.form,
            upload = layui.upload;

        var laydate = layui.laydate;

        //执行一个laydate实例
        //编辑表单的日期
        laydate.render({

            elem: '#birthday' //指定元素

            , min: minDate()
            , max: maxDate()
            , btns: ['clear', 'confirm']

        });
        //执行一个laydate实例

        //添加表单的日期

        laydate.render({

            elem: '#addBirthday' //指定元素
            , min: minDate()
            , max: maxDate()
            , btns: ['clear', 'confirm']

        });

        function maxDate() {
            var now = new Date();
            return (now.getFullYear() - 18) + "-" + (now.getMonth() + 1) + "-" + now.getDate();
        }

        function minDate() {
            var now = new Date();
            return (now.getFullYear() - 100) + "-" + (now.getMonth() + 1) + "-" + now.getDate();
        }

        var table_User = table.render({
            elem: '#test'
            , toolbar: '#toolbarDemo'
            , url: '/user/getPage'
            , cols: [
                [
                    {type: 'checkbox'}
                    , {field: 'id', width: 80, title: 'ID', sort: true, align: "center"}
                    , {field: 'username', width: 140, title: '用户名', align: "center"}
                    , {field: 'password', width: 80, title: '密码', align: "center"}
                    , {
                    field: 'gender', width: 80, title: '性别', align: "center",
                    templet: function (d) {
                        if (d.gender == 0) {
                            return '女';
                        } else if (d.gender == 1) {
                            return '男';
                        } else {
                            return '未知'
                        }
                    }
                }
                    , {field: 'birthday', width: 120, title: '出生日期', align: "center"}
                    , {field: 'phone', width: 140, title: '电话号码', align: "center"}
                    , {field: 'right', title: '操作', toolbar: '#barDemo', width: '9%', align: 'center'}

                ]
            ]
            , page: true
            , limit: 10
            , limits: [5, 10, 15, 20, 25, 30]
        });
        //查询
        form.on('submit(formDemo)', function (data) {
            table.reload('test', {
                where: {
                    username: data.field.username
                }
            });
            return false;
        });
        //监听表格复选框选择
        table.on('checkbox(demo)', function (obj) {
            console.log(obj.tr)
        });
        //监听工具条
        table.on('tool(demo)', function (obj) {
            var data = obj.data;

            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    console.log(data.id)
                    var data_t = {
                        "id": data.id,
                    };
                    $.post("/user/deleteUser",
                        {"id": data.id},
                        function (res) {
                            if (res.code == 0) {
                                layer.msg("删除成功");
                                layer.closeAll();
                                table.reload('test', {
                                        url: '/user/getPage',
                                        page: {
                                            curr: 1 //重新从第 1 页开始
                                        },
                                    }
                                );

                            }
                        });

                    layer.close(index);
                });
            } else if (obj.event === 'edit') {

                $("#editUser")[0].reset();
                layer.open({

                    type: 1,
                    title: "修改用户",
                    area: ['500px', '600x'], //宽高
                    // closeBtn: 0, //不显示关闭按钮
                    // scrollbar: false, //禁止浏览器出现滚动条
                    // resize: false, //禁止拉伸
                    // move: false, //禁止拖拽
                    // shade: 0.8, //遮罩
                    // shadeClose: true, //点击遮罩关闭当前页面
                    content: $("#editUser"), //这里content是一个Url
                    success: function (layero, index) {//弹出层打开后的回调函数,数据回显
                        //updateNumber为弹出层id,eaccidentNumber为数据表格的field属性
                        console.log(data);
                        $('#id').val(data.id);
                        $('#username').val(data.username);
                        $('#password').val(data.password);
                        $("#gender").each(function () {
                            // this代表的是<option></option>，对option再进行遍历
                            $(this).children("option").each(function () {
                                // 判断需要对那个选项进行回显
                                if (this.value == data.gender) {
                                    console.log("1" + $(this).text());
                                    // 进行回显
                                    $(this).attr("selected", "selected");
                                }
                            });
                        });
                        form.render("select");
                        $('#birthday').val(data.birthday);
                        $('#phone').val(data.phone);
                    },
                })
            }
        });
        <!--toolbar添加删除功能-->
        table.on('toolbar(demo)', function (obj) {
            var check = table.checkStatus(obj.config.id)
                , data = check.data;
            switch (obj.event) {
                case 'add':
                    $("#addUser")[0].reset();
                    layer.open({

                        title: '添加用户',
                        type: 1,
                        area: ['500px', '400px'],
                        content: $("#addUser")
                    });
                    break;
                case 'dels':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else {
                        var ids = [];
                        for (var i = 0; i < data.length; i++) {
                            ids[i] = data[i].id;
                        }
                        console.log(ids);
                        layer.confirm('真的删除行么', function (index) {
                            $.ajax({
                                url: '/user/batchDeleteUser',//路径
                                type: 'post',//post/get
                                data: {ids: ids},//传给后台的参数
                                dataType: 'json',//相应的数据类型,
                                success: function (result) {
                                    //成功响应函数
                                    if (result.code == 0) {
                                        layer.closeAll();
                                        table.reload('test', {
                                                url: '/user/getPage',
                                                page: {
                                                    curr: 1 //重新从第 1 页开始
                                                },
                                            }
                                        );
                                        layer.msg(result.msg, {icon: 6});
                                    } else {
                                        layer.msg(result.msg, {icon: 5});
                                    }
                                }
                            });
                        });
                    }
                    break;
            }
        });


        //监听编辑表单的提交
        form.on('submit(editSubmit)', function (data) {
            data = data.field;
            console.log(data)
            var data_t = {
                "id": data.id,
                "username": data.username,
                "password": data.password,
                "gender": data.gender,
                "birthday": data.birthday,
                "phone": data.phone,
            }
            //console.log(data)
            console.log(data_t)
            $.ajax({
                url: "/user/updateUser",
                method: "post",
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(data_t),
                success: function (res) {
                    if (res.code == 0) {
                        layer.msg("修改成功");
                        layer.closeAll();
                        table_User.reload();

                    }
                }
            })
            return false;
        });
        form.verify({
            newmobile: function (value) {
                if (value.length != 11) {
                    return '新手机号必须为11位合法数字';
                }
                var reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
                if (reg.test(value)) {
                    // return '手机号码格式正确';
                } else {
                    return '非法手机号';
                }
            },

        });

        //监听添加表单的提交
        form.on('submit(addSubmit)', function (data) {
            data = data.field;
            console.log(data);
            var data_t = {

                "username": data.addUsername,
                "password": data.addPassword,
                "gender": data.addGender,
                "birthday": data.addBirthday,
                "phone": data.addPhone,

            }

            $.ajax({
                url: "/user/addUser",
                method: "post",
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(data_t),
                success: function (res) {
                    if (res.code == 0) {
                        layer.msg("添加成功");
                        layer.closeAll();
                        table_User.reload();

                    }
                }
            })
            return false;
        });


    })

</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="toolbarDemo">
    <a class="layui-btn layui-btn-xs" lay-event="add">添加</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="dels">删除</a>
</script>
</body>
</html>